from flask import Blueprint, request, jsonify
from datetime import datetime
import json

from user.model import User
from order.model import Order
from order.model import Deliver
from order.model import Print
from order.model import db
from admin.model import Admin

from database import R
from database import global_mode

order_blueprint = Blueprint('order', __name__)


def getUid():
    uid = R.get(request.headers.get('token'))
    if uid is None:
        return None
    else:
        return uid


@order_blueprint.before_request
def before_eq():
    if getUid() is None:
        return {
                   'errmsg': 'token expired'
               }, 401


@order_blueprint.route('/orders_dfh', methods=['GET'])
def orders_dfh():
    if request.method == 'GET':
        uid = getUid()

        orders = Order.query.filter(Order.userid == uid, Order.status <= 0.7).order_by(Order.id.desc()).all()
        order_list = []
        for order in orders:
            desca = ''
            descb = ''
            if order.type == 'deliver':
                desca = '快递单号: ' + order.desca
                descb = '取件码: ' + order.descb
            else:
                desca = '文件名: ' + order.desca
            order_list.append({
                'id': order.id,
                'type': order.type,
                'desca': desca,
                'descb': descb,
                'status': order.status,
                'time': order.time.strftime('%Y年%m月%d日 %H:%M:%S')
            })
        return {
                   'dfh': order_list
               }, 200
    else:
        return {
                   'errmsg': 'http type error, must be GET'
               }, 201


@order_blueprint.route('/orders_dsh', methods=['GET', 'POST'])
def orders_dsh():
    if request.method == 'GET':
        uid = getUid()

        orders = Order.query.filter(Order.userid == uid, Order.status == 1).order_by(Order.id.desc()).all()
        order_list = []
        for order in orders:
            desca = ''
            descb = ''
            if order.type == 'deliver':
                desca = '快递单号: ' + order.desca
                descb = '取件码: ' + order.descb
            else:
                desca = '文件名: ' + order.desca
            order_list.append({
                'id': order.id,
                'type': order.type,
                'desca': desca,
                'descb': descb,
                'status': order.status,
                'time': order.time.strftime('%Y年%m月%d日 %H:%M:%S')
            })
        return {
                   'dsh': order_list
               }, 200
    else:
        orderid = request.form.get('id')
        order = Order.query.filter_by(id=orderid).first()
        order.status = 2
        order.con_time = datetime.now()
        staff = Admin.query.filter_by(eid=order.eid).first()
        staff.score = staff.score + order.money
        db.session.commit()
        return {
                   'msg': '用户确认收货成功'
               }, 200


@order_blueprint.route('/orders_all', methods=['GET'])
def orders_all():
    if request.method == 'GET':
        args = request.args.to_dict()
        if len(args) == 1 and 'page' in args:
            uid = getUid()
            orders = Order.query.filter(Order.userid == uid).order_by(Order.id.desc()).all()
            page = int(request.args.get('page'))
            total_pages_count = 0
            if len(orders) % 4 == 0:
                total_pages_count = len(orders) // 4  # 总页数
            else:
                total_pages_count = len(orders) // 4 + 1  # 总页数
            left = total_pages_count - page  # 剩余页数
            order_list = []
            need_count = 0  # 一共需要几个 因为最后一页可能不是4个
            if page * 4 <= len(orders):
                need_count = 4  # 不是最后一页
            else:
                need_count = page * 4 - len(orders)
            # print('要第%d页，共有%d页，还剩%d页，这一页返回%d个' % (page, total_pages_count, left, need_count))
            # print("切片: " + str(((page - 1) * 4)) + " : " + str(((page - 1) * 4) + need_count))
            for order in orders[((page - 1) * 4):(((page - 1) * 4) + need_count)]:  # 切片找出列表元素
                desca = ''
                descb = ''
                if order.type == 'deliver':
                    desca = '快递单号: ' + order.desca
                    descb = '取件码: ' + order.descb
                elif order.type == 'print':
                    desca = '文件名: ' + order.desca
                else:
                    desca = '充值金额: ' + str(order.money)
                order_list.append({
                    'id': order.id,
                    'type': order.type,
                    'desca': desca,
                    'descb': descb,
                    'status': order.status,
                    'time': order.time.strftime('%Y年%m月%d日 %H:%M:%S')
                })
            return {
                       'page': left,
                       'all': order_list
                   }, 200
        else:
            return {
                       'errmsg': 'GET type error, must be 1 params("page")'
                   }, 201


@order_blueprint.route('/do_deliver', methods=['POST'])
def deliver():
    def getqkd(type):
        with open('user/money.json')as f:
            content = f.read()
            obj = json.loads(content)
            f.close()
            if type == '大件快递':
                return obj['dkd']
            elif type == '中件快递':
                return obj['zkd']
            elif type == '小件快递':
                return obj['xkd']

    if request.method == 'POST':
        uid = getUid()

        user = User.query.filter_by(id=uid).first()
        money = user.money
        if global_mode == 1:
            if money - getqkd(request.form.get('type')) < 0:
                return {
                           'errmsg': '当前账户余额不足，请先充值！'
                       }, 201

        # 创建订单
        order = Order(userid=uid, type='deliver', desca=request.form.get('danhao'), descb=request.form.get('qvjianma'),
                      status=0, time=datetime.now(), money=str(getqkd(request.form.get('type'))))
        db.session.add(order)
        db.session.flush()  # 这样可以直接拿ID
        orderid = order.id
        db.session.commit()

        if global_mode == 1:
            money = order.money
            user = User.query.filter_by(id=getUid()).first()
            user.money = user.money - float(money)

        # 创建取快递对象
        deliver = Deliver(orderid=orderid, userid=uid, delivernum=request.form.get('danhao'),
                          yizhan=request.form.get('yizhan'), code=request.form.get('qvjianma'),
                          addindex=request.form.get('addrindex'), type=request.form.get('type'),
                          note=request.form.get('note'), res_time=request.form.get('yuyuetime'))
        db.session.add(deliver)
        db.session.commit()
        return {
                   'msg': '创建取快递订单成功'
               }, 200


@order_blueprint.route('/do_print', methods=['POST'])
def do_print():
    def getddy():
        with open('user/money.json')as f:
            content = f.read()
            obj = json.loads(content)
            f.close()
            return obj['ddy']
    def getdyps():
        with open('user/money.json')as f:
            content = f.read()
            obj = json.loads(content)
            f.close()
            return obj['dyps']

    if request.method == 'POST':
        uid = getUid()

        user = User.query.filter_by(id=uid).first()
        money = user.money
        totalmoney = float(getddy()) * int(request.form.get('number')) + float(getdyps())

        if global_mode == 1:
            if money - totalmoney < 0:
                return {
                           'errmsg': '当前账户余额不足，请先充值！'
                       }, 201

        # 创建订单
        order = Order(userid=uid, type='print', desca=request.form.get('fname'), descb='',
                      status=0, time=datetime.now(), money=str(totalmoney))
        db.session.add(order)
        db.session.flush()  # 这样可以直接拿ID
        orderid = order.id
        db.session.commit()

        if global_mode == 1:
            money = order.money
            user = User.query.filter_by(id=getUid()).first()
            user.money = user.money - float(money)
        p = Print(orderid=orderid, userid=uid, fid=request.form.get('fid'),
                      fname=request.form.get('fname'), addindex=request.form.get('addrindex'),
                      count=request.form.get('number'), note=request.form.get('note'),
                      res_time=request.form.get('yuyuetime'), ziti=1 if request.form.get('ziti') == 'true' else 0,
                      station=request.form.get('station'))
        db.session.add(p)
        db.session.commit()
        return {
                   'msg': '创建打印订单成功！'
               }, 200
